//
//  HomeOwnViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
import SwiftUI

class HomeAiViewModel : BaseViewModel {
    @Published var items = [DiaryBean]()
    @Published var status = ""
    @Published var aiRole: AiRoleBean? = nil
    
    
    init(item: HomeTableItem) {
        super.init()
        self.addObserve(self,.delDiary) { (selfInstance, bean: DiaryBean) in
            withAnimation {
                if let index = selfInstance.items.firstIndex(where: { $0.objectId == bean.objectId }) {
                    selfInstance.items.remove(at: index)
                }
            }
        }
        self.addObserve(self, .aiDiary) { (selfInstance, id: String) in
            //ai 日记更新
            if item.id == id {
                showLog("执行更新ai日记")
                //需要同一个才能更新
                selfInstance.items.removeAll()
                selfInstance.getData(true,item : item)
            }
        }
    }
    
    func getData(_ isRefresh: Bool = false, item: HomeTableItem) {
        requestList(isRefresh: isRefresh) {
            try check(userManager.isVip() || isExamine(), "心灵日记，需要升级Pro才能使用")
            let list = try await BackupsManager.shared.getDelegateDiary()?.queryDiaryAi(
                userId: userManager.getUserId(),
                roleId: item.id,
                keyword: nil,
                pageNo: self.pageNo,
                pageSize: self.pageSize
            ) ?? []
            try check(!isRefresh || !list.isEmpty, "\(String(describing: item.name))还没有写日记哦")
            return list
        } suc: { diarys in
            self.status = ""
            self.items.append(contentsOf: diarys)
        } fail: {
            self.status = $0.message
        }
    }
    
    func reset() {
        isInit = false
        items.removeAll()
    }
}
